from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import authenticate
from django.utils.translation import gettext_lazy as _
from .models import User, UserRole

class CustomUserCreationForm(UserCreationForm):
    """自定义用户创建表单"""
    phone = forms.CharField(
        label=_('手机号'),
        max_length=11,
        required=False,
        help_text=_('请输入11位手机号码'),
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入手机号码')})
    )
    
    class Meta:
        model = User
        fields = ('username', 'phone', 'password1', 'password2')
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入用户名')}),
        }

class SuperAdminUserCreationForm(UserCreationForm):
    """超级管理员创建用户表单"""
    phone = forms.CharField(
        label=_('手机号'),
        max_length=11,
        required=False,
        help_text=_('请输入11位手机号码'),
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入手机号码')})
    )
    
    role = forms.ChoiceField(
        label=_('角色'),
        choices=UserRole.choices,
        initial=UserRole.NORMAL,
        help_text=_('选择用户角色'),
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    class Meta:
        model = User
        fields = ('username', 'phone', 'email', 'role', 'password1', 'password2')
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入用户名')}),
            'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': _('请输入邮箱')}),
        }
    
    def save(self, commit=True):
        """保存用户时设置角色"""
        user = super().save(commit=False)
        user.role = self.cleaned_data['role']
        if commit:
            user.save()
        return user

class CustomUserChangeForm(UserChangeForm):
    """自定义用户修改表单"""
    phone = forms.CharField(
        label=_('手机号'),
        max_length=11,
        required=False,
        help_text=_('请输入11位手机号码'),
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )
    
    # 为了支持密码修改，需要添加密码字段
    password = forms.CharField(
        label=_('密码'),
        required=False,
        help_text=_('留空表示不修改密码'),
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': _('留空表示不修改密码')})
    )
    
    confirm_password = forms.CharField(
        label=_('确认密码'),
        required=False,
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': _('再次输入密码')})
    )
    
    class Meta:
        model = User
        fields = ('username', 'phone', 'email', 'first_name', 'last_name')
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'}),
        }
    
    def clean(self):
        """验证表单数据"""
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')
        
        # 如果填写了密码，则需要验证两次密码是否一致
        if password:
            if not confirm_password:
                self.add_error('confirm_password', _('请确认密码'))
            elif password != confirm_password:
                self.add_error('confirm_password', _('两次输入的密码不一致'))
        
        return cleaned_data
    
    def save(self, commit=True):
        """保存用户信息，包括密码修改"""
        user = super().save(commit=False)
        password = self.cleaned_data.get('password')
        
        # 如果填写了密码，则更新密码
        if password:
            user.set_password(password)
        
        if commit:
            user.save()
        
        return user

class SuperAdminUserChangeForm(CustomUserChangeForm):
    """超级管理员修改用户表单（包含角色字段）"""
    role = forms.ChoiceField(
        label=_('角色'),
        choices=UserRole.choices,
        help_text=_('选择用户角色'),
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    class Meta(CustomUserChangeForm.Meta):
        fields = ('username', 'phone', 'email', 'role', 'first_name', 'last_name')
    
    def save(self, commit=True):
        """保存用户时设置角色"""
        user = super().save(commit=False)
        user.role = self.cleaned_data['role']
        
        if commit:
            user.save()
        
        return user

class UserLoginForm(forms.Form):
    """用户登录表单"""
    username = forms.CharField(
        label=_('用户名'),
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('请输入用户名')})
    )
    password = forms.CharField(
        label=_('密码'),
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': _('请输入密码')})
    )
    
    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        
        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError(_('用户名或密码错误'))
            if not user.is_active:
                raise forms.ValidationError(_('用户已禁用'))
        
        return cleaned_data